package com.excel.manager.excel;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

/**
 * @author ravi
 * */
public class Utilities {

    public static Map<Object, Integer> createHeaderMap(Sheet sheet, int headerRow) {
        Map<Object, Integer> excelHeaderMap = new HashMap<Object, Integer>();

        Row row = sheet.getRow(headerRow);
        for (Cell cell : row) {
            excelHeaderMap.put(getCellValue(cell), cell.getColumnIndex());
        }
        return excelHeaderMap;
    }

    public static Object getCellValue(Cell cell) {

        if (cell == null) {
            return null;
        }

        if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            return "";
        }

        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (DateUtil.isCellDateFormatted(cell)) {
                return cell.getDateCellValue();

            } else {
                return cell.getNumericCellValue();
            }
        }

        if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return cell.getStringCellValue().replaceAll("'", "");
        }

        return null;
    }

    public static int getPhysicalNumberOfRows(Sheet sheet) {
        int notNullCount = 0;
        for (Row row : sheet) {
            for (Cell cell : row) {
                if (cell.getCellType() != Cell.CELL_TYPE_BLANK) {
                    if (cell.getCellType() != Cell.CELL_TYPE_STRING || cell.getStringCellValue().length() > 0) {
                        notNullCount++;
                        break;
                    }
                }
            }
        }
        return notNullCount;
    }

    public static void insertRow(Sheet sheet, Map<Integer, Object[]> data) {
        Set<Integer> keyset = data.keySet();

        for (Integer key : keyset) {
            Row row = sheet.createRow(getPhysicalNumberOfRows(sheet));
            Object[] objArr = data.get(key);

            int cellnum = 0;
            for (Object object : objArr) {
                Cell cell = row.createCell(cellnum++);

                if (object instanceof java.util.Date) {

                    cell.setCellValue((java.util.Date) object);
                } else if (object instanceof Boolean) {

                    cell.setCellValue((Boolean) object);
                } else if (object instanceof String) {

                    cell.setCellValue((String) object);
                } else if (object instanceof Double) {

                    cell.setCellValue((Double) object);
                } else if (object instanceof java.util.Date) {

                }
            }
        }
    }
}
